<template>
  <div>
    <div align="right" style="margin-bottom: 15px">
      <el-button type="primary" @click="openAdd">新增用户</el-button>
    </div>
    <el-table :data="tableData" height="503" border>
      <el-table-column prop="jobNumber" label="用户工号" align="center" />
      <el-table-column prop="name" label="用户姓名" align="center" />
      <el-table-column prop="userType" label="用户职称" align="center" />
      <el-table-column prop="departmentName" label="所属科室" align="center" />
      <el-table-column prop="authority" label="账号权限" align="center" />
      <el-table-column prop="userRole" label="分配角色" align="center" />
      <el-table-column prop="userCode" label="员工编号" align="center" />
      <el-table-column prop="email" label="员工账号" align="center" />

      <el-table-column prop="phoneNum" label="联系方式" align="center" />
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button type="text" @click="openEdit(scope.row)">
            编辑用户
          </el-button>
          <el-button type="text" @click="openEditPassword(scope.row)">
            重置密码
          </el-button>
          <el-button type="text" @click="openDel(scope.row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="page.current"
      :page-sizes="[10, 20, 30, 40, 50, 60, 70, 80, 90]"
      :page-size.sync="page.limit"
      layout="sizes, prev, pager, next ,total"
      :total="page.total"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      :title="title"
      :visible.sync="addVisible"
      width="700px"
      custom-class="add-dialog"
      center
    >
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="80px"
        style="padding: 0 10px 0 0px"
        :rules="formRule"
      >
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="用户工号" prop="jobNumber">
              <el-input v-model="editForm.jobNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户编号">
              <el-input v-model="editForm.userCode" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickname">
              <el-input v-model="editForm.nickname" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phoneNum">
              <el-input v-model="editForm.phoneNum" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="用户职称" prop="userType">
              <el-input v-model="editForm.userType" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属科室" prop="deptId">
              <el-select v-model="editForm.deptId" style="width: 100%">
                <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="账号权限" prop="authority">
              <el-select v-model="editForm.authority" style="width: 100%">
                <el-option value="普通用户"> </el-option>
                <el-option value="医院管理员"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报权限" prop="uploadAuthority">
              <el-select v-model="editForm.uploadAuthority" style="width: 100%">
                <el-option value="上报管理员"> </el-option>
                <el-option value="审核管理员"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="分配角色" prop="userRole">
              <!-- <el-input v-model="editForm.userRole"></el-input> -->
              <el-select v-model="editForm.userRole" style="width: 100%">
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="!editForm.id" :span="12">
            <el-form-item label="用户账号" prop="username">
              <el-input v-model="editForm.username" />
            </el-form-item>
          </el-col>
          <el-col v-if="!editForm.id" :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="editForm.password" type="password" />
              <!-- :disabled="editForm.id ? true : false"
                :class="editForm.id ? 'edit-password' : ''" -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm"> 确 定 </el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="重置密码"
      :visible.sync="passwordVisible"
      width="30%"
      custom-class="add-dialog"
      center
    >
      <el-form
        :model="passwordForm"
        label-width="80px"
        style="padding: 0 40px 10px 0px"
      >
        <el-form-item label="密码" prop="password">
          <el-input v-model="passwordForm.password" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordVisible = false">取 消</el-button>
        <el-button type="primary" @click="passwordConfirm()"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="确认是否删除"
      :visible.sync="deleteVisible"
      width="30%"
      custom-class="del-dialog"
    >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="delConfirm()"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import md5 from 'js-md5'
import {
  users1New,
  updateAppUserGNew,
  register1New,
  findRolesByUserAllNew,
  deleteUsers,
  resetPassword
} from '@/api/back-management/user-manage/employee'
import { hospitalIdNew } from '@/api/back-management/user-manage/dept'
import { getToken } from '@/utils/auth'
export default {
  name: 'Employee',
  props: {
    hospitalId: {
      type: String,
      default: '37'
    },
    regionId: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      tableData: [],
      deptList: [],
      roleList: [],
      addVisible: false,
      deleteVisible: false,
      passwordVisible: false,
      title: '',
      editForm: {},
      delForm: {},
      passwordForm: {},
      page: {
        current: 1,
        limit: 10,
        total: 0
      },
      formRule: {
        jobNumber: [{ required: true, message: '请输入用户工号', trigger: 'blur' }],
        nickname: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
        phoneNum: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
        userType: [{ required: true, message: '请输入用户职称', trigger: 'blur' }],
        deptId: [{ required: true, message: '请输入所属科室', trigger: 'change' }],
        authority: [{ required: true, message: '请输入账号权限', trigger: 'change' }],
        uploadAuthority: [{ required: true, message: '请输入上报权限', trigger: 'change' }],
        userRole: [{ required: true, message: '请输入角色', trigger: 'change' }],
        username: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.usersNew()
    this.hospitalIdNew()
    this.findRolesByUserAllNew()
  },
  methods: {
    usersNew() {
      users1New({
        hospitalId: this.hospitalId,
        pageSize: this.page.limit,
        pageNum: this.page.current,
        token: getToken()
      }).then((res) => {
        if (!(typeof res == 'string' && res.indexOf('云服务接口错误') > -1)) {
          this.tableData = res.list
          this.page.total = res.total
        }
      })
    },
    handleSizeChange(val) {
      this.page.limit = val
      this.page.current = 1
      this.usersNew()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.usersNew()
    },
    hospitalIdNew() {
      hospitalIdNew({
        hospitalId: this.hospitalId,
        pageNum: 1,
        pageSize: 20,
        token: getToken()
      }).then((res) => {
        this.deptList = res.data.list
      })
    },
    findRolesByUserAllNew() {
      findRolesByUserAllNew({
        hospitalId: this.hospitalId,
        token: getToken()
      }).then((res) => {
        let arr = []
        for (const key in res) {
          if (Array.isArray(res[key])) {
            arr.push(...res[key])
          }
        }
        this.roleList = arr
      })
    },
    openAdd() {
      this.addVisible = true
      this.title = '新增医院用户'
      this.editForm = {}
    },
    openEdit(row) {
      this.addVisible = true
      this.title = '修改医院用户'
      this.editForm = JSON.parse(JSON.stringify(row))
      this.editForm.nickname = this.editForm.name
      this.editForm.username = this.editForm.email
    },
    openEditPassword(row) {
      this.passwordForm.id = row.id
      this.passwordForm.token = getToken()
      this.passwordVisible = true
    },
    openDel(row) {
      this.deleteVisible = true
      this.delForm.userIds = [row.id]
      this.delForm.token = getToken()
    },
    confirm() {
      this.editForm.token = getToken()
      this.deptList.forEach((item) => {
        if (this.editForm.deptId == item.id) {
          this.editForm.departmentName = item.name
        }
      })
      this.roleList.forEach((item) => {
        if (this.editForm.userRole == item.name) {
          this.editForm.roleName = item.name
          this.editForm.roleId = item.id
        }
      })
      if (this.editForm.id) {
        this.edit()
      } else {
        this.add()
      }
    },
    edit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          updateAppUserGNew(this.editForm).then((res) => {
            if (typeof res == 'string' && res.indexOf('云服务接口错误') > -1) {
              let err_message = '用户没有权限修改当前医院用户！'
              if (res.indexOf(err_message) > -1) {
                this.$message.error(err_message)
              } else {
                this.$message.error('修改用户失败')
              }
            } else {
              this.$message.success('修改用户成功')
              this.usersNew()
              this.addVisible = false
            }
          })
        }
      })
    },
    add() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.editForm.hospitalId = this.hospitalId
          this.editForm.regionId = this.regionId
          register1New(this.editForm).then((res) => {
            if (res.code == 0) {
              this.$message.success('新增用户成功')
              this.page.current = 1
              this.usersNew()
              this.addVisible = false
            } else if (res.code == 9999 || !res.code) {
              const err_message1 = '用户没有权限添加当前医院用户！'
              const err_message2 = '用户账号已经存在，不能新增！'
              if (res.error === err_message1) {
                this.$message.error(err_message1)
              } else if (res.error === err_message2) {
                this.$message.error(err_message2)
              } else {
                this.$message.error('新增用户失败')
              }
            }
          })
        }
      })
    },
    passwordConfirm() {
      this.passwordForm.psdmd5 = md5(this.passwordForm.password)
      resetPassword({
        id: this.passwordForm.id,
        password: this.passwordForm.psdmd5
      }).then((res) => {
        if (typeof res === 'string' && res.indexOf('云服务接口错误') > -1) {
          this.$message.error('重置密码失败')
        } else {
          this.$message.success('重置密码成功')
          this.usersNew()
          this.passwordVisible = false
        }
      })
    },
    delConfirm() {
      deleteUsers(this.delForm).then((res) => {
        if (typeof res == 'string' && res.indexOf('云服务接口错误') > -1) {
          const err_message = '用户没有权限删除当前医院用户！'
          if (res.indexOf(err_message) > -1) {
            this.$message.error(err_message)
          } else {
            this.$message.error('删除用户失败')
          }
        } else {
          this.$message.success('删除用户成功')
          this.usersNew()
          this.deleteVisible = false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .add-dialog {
  .el-dialog__body {
    padding-bottom: 0;
  }
}
/deep/ .del-dialog .el-dialog__body {
  padding: 0 !important;
}
</style>
